# Create your views here.
import json
import re

from django.conf import settings
from django.contrib.auth import login, authenticate
from django.views import View
from django.http import JsonResponse
from django.contrib.auth import logout
from django_redis import get_redis_connection

from ihome.libs.qiniuyun.qiniu_storage import storage
from users.models import User
from ihome.utils.view import LoginRequiredMixin


class RegisterView(View):

    def post(self, request):
        """用户注册"""
        dict = json.loads(request.body.decode())
        mobile = dict.get('mobile')
        phonecode_client = dict.get('phonecode')
        password = dict.get('password')
        password2 = dict.get('password2')

        # 校验参数整体
        if not all([mobile, phonecode_client, password, password2]):
            return JsonResponse({
                'errno': 4002,
                'errmsg': '缺少必传参数'
            })

        # password检验
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return JsonResponse({'errno': '4004',
                                 'errmsg': 'password格式有误'})

        if password != password2:
            return JsonResponse({'errno': '4004',
                                 'errmsg': '两次输入不对'})
        # 6.mobile检验
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'errno': '4004',
                                 'errmsg': 'mobile格式有误'})

        redis_conn = get_redis_connection('verify_code')

        # 从 redis中取值
        phonecode_server = redis_conn.get('sms%s' % mobile)
        if not phonecode_server:
            return JsonResponse({
                'errno': '4004',
                'errmsg': '短信验证码过期'
            })
        if phonecode_client != phonecode_server.decode():
            return JsonResponse({
                'errno': '4004',
                'errmsg': '验证码有误'
            })
        # 保存到数据库
        try:
            user = User.objects.create_user(username=mobile,
                                            mobile=mobile,
                                            password=password)
        except Exception as e:
            return JsonResponse({
                'errno': '4001',
                'errmsg': '保存到数据库失败'
            })
        return JsonResponse({
            'errno': '0',
            'errmsg': '注册成功'
        })


class LoginView(View):

    def post(self, request):
        '''实现登录接口'''
        # 1.接收参数
        dict = json.loads(request.body.decode())
        mobile = dict.get('mobile')
        password = dict.get('password')

        # 2.校验(整体 + 单个)
        if not all([mobile, password]):
            return JsonResponse({'errno': '4002',
                                 'errmsg': '缺少必传参数'})

        # 3.验证是否能够登录
        user = authenticate(username=mobile,
                            password=password)


        # 判断是否为空,如果为空,返回
        if user is None:
            return JsonResponse({'errno': '4004',
                                 'errmsg': '手机号或者密码错误'})

        # 4.状态保持
        login(request, user)

        # 5.返回json
        response = JsonResponse({'errno': '0',
                                 'errmsg': '登陆成功'})

        response.set_cookie('username',
                            request.user.username,
                            max_age=3600 * 24 * 14)
        return response

    def delete(self, request):
        """实现退出登录逻辑"""

        # 清理 session
        logout(request)

        # 创建 response 对象.
        response = JsonResponse({'errno': '0',
                                 'errmsg': '已登出'})

        # 调用对象的 delete_cookie 方法, 清除cookie
        response.delete_cookie('username')

        # 返回响应
        return response

    def get(self, request):
        """判断是否登录"""

        if request.user.is_authenticated:

            return JsonResponse({
                "errno": '0',
                "errmsg": "已登录",
                "data": {
                    "name": request.user.username,
                    "user_id": request.user.id
                }})

        else:
            return JsonResponse({
                "errno": '4101',
                "errmsg": '未登录'
            })


class UserInfoView(LoginRequiredMixin, View):

    def get(self, request):
        '''只有登录用户才能进入该类视图 用户中心'''

        dict = {
            "name": request.user.username,
            "mobile": request.user.mobile,
            "avatar": request.user.avatar,
            "user_id": request.user.id,
            "create_time": request.user.date_joined,
        }

        return JsonResponse({'errno': '0',
                             'errmsg': 'ok',
                             'data': dict})


class UserNameModificationView(LoginRequiredMixin, View):
    """用户名修改"""

    def put(self, request):
        dict = json.loads(request.body.decode())
        name = dict.get('name')

        if not name:
            return JsonResponse({'errno': '400',
                                 'errmsg': '缺少必传参数'})

        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', name):
            return JsonResponse({'errno': '400',
                                 'errmsg': '用户名不满足格式要求'})

        try:
            request.user.username = name
            request.user.save()
        except Exception as e:
            return JsonResponse({'errno': '400',
                                 'errmsg': '保存失败'})
        response = JsonResponse({'errno': '0',
                                 'errmsg': '修改成功'
                                 })
        response.set_cookie('name',
                            request.user.username,
                            max_age=3600 * 24 * 14)
        return response


class UserRealNameAuthentication(LoginRequiredMixin, View):
    """用户实名认证"""

    def post(self, request):
        dict = json.loads(request.body.decode())
        real_name = dict.get('real_name')
        id_card = dict.get('id_card')

        if not all([real_name, id_card]):
            return JsonResponse({'errno': '400',
                                 'errmsg': '缺少必传参数'})

        if not re.match(r'^[\u4E00-\u9FA5]{2,4}$|^[a-zA-Z_-]{5,20}$', real_name):
            return JsonResponse({'errno': '400',
                                 'errmsg': '真实姓名不满足格式要求'})

        if not re.match(r'^\d{17}[\d|x]$', id_card):
            return JsonResponse({'errno': '4004',
                                 'errmsg': '身份证号码不满足格式要求'})

        try:

            request.user.real_name=real_name
            request.user.id_card=id_card
            request.user.save()
        except Exception as e:
            return JsonResponse({'errno': '4001',
                                 'errmsg': '保存数据到数据库失败'})

        return JsonResponse({'errno': '0',
                             'errmsg': '认证信息保存成功'})

    def get(self, request):
        # 判断当前用户是否实名认证
        real_name = request.user.real_name
        id_card = request.user.id_card

        if not all([real_name, id_card]):
            return JsonResponse({'errno': '4002',
                                 'errmsg': '没有实名认证'})

        return JsonResponse({'errno': '0',
                             'data': {'real_name': real_name,
                                      'id_card': id_card},
                             'errmsg': 'ok'})


class AddtouxiangView(LoginRequiredMixin, View):
    """上传头像"""

    def post(self, request):
        # dict = json.loads(request.body.decode())
        avatar = request.FILES.get('avatar')

        # avatar = dict.get('avatar')
        if not avatar:
            return JsonResponse({
                'errno': '4002',
                'errmsg': '缺少必传参数'
            })
        file_data = avatar.read()
        retusult = storage(file_data)
        try:
            request.user.avatar = settings.QINIU_URL + retusult
            request.user.save()
        except Exception as e:
            return JsonResponse({'errno': '4001',
                                 'errmsg': '保存数据到数据库失败'})

        dict = {
            "avatar_url": settings.QINIU_URL + retusult
        }

        return JsonResponse({
            "data": dict,
            "errno": '0',
            "errmsg": "头像上传成功"
        })
